package Thread;

import java.util.concurrent.atomic.AtomicInteger;

public class ArrayQueue {

    private int size = 16;

    private int[] item = new int[size];

    private final Object full = new Object();

    private final Object empty = new Object();

    private int put;

    private int get;

    private int count;

    public void put(int i) {
        synchronized (full) {
            while (count == size) {
                try {
                    full.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        synchronized (empty) {
            item[put++] = i;
            count++;
            if (put == size) {
                put = 0;
            }
            empty.notify();
        }
    }

    public int get() {

        synchronized (empty) {
            while (count == 0) {
                try {
                    empty.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        int result =0;
        synchronized (full){
            result = item[get];
            item[get] = 0;
            count--;
            get++;
            if (get == size) {
                get = 0;
            }
            full.notify();
        }
        return result;
    }

    public static void main(String[] args) throws InterruptedException {
        ArrayQueue arrayQueue = new ArrayQueue();
        Thread thread = new Thread(() -> {
            int count = 100;
            while (count > 0) {
                arrayQueue.put(count--);
            }
        });
        thread.start();
        Thread thread1 = new Thread(() -> {
            int count = 100;
            while (count > 0) {
                System.out.println(arrayQueue.get());
            }
        });
        thread1.start();
        thread.join();
        thread1.join();
    }
}
